/*******************************************************************************
 * Package: com.song.common.idempotent
 * Type:    IdempotentService
 * Date:    2025-07-24 21:34
 *
 * Copyright (c) 2025 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.common.idempotent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 功能描述：  幂等控制工具类
 *
 * @author Songxianyang
 * @date 2025-07-24 21:34
 */
@Service
public class IdempotentService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DefaultRedisScript<Long> idempotentScript;

    /**
     *  0标识存在  1标识不存在
     * @param idempotentKey  key
     * @param expireSeconds  过期时间 s
     * @return 0
     */
    public boolean checkRequest(String idempotentKey, int expireSeconds) {
        List<String> keys = Collections.singletonList(idempotentKey);
        Long result = redisTemplate.execute(
                idempotentScript,
                keys,
                "processed",
                String.valueOf(expireSeconds)
        );
        //lua 返回 0  表示redis 中存在
        return result != null && result == 1;
    }
}
